package com.coisshi.base.module.oss.controller;

import cn.dev33.satoken.util.SaResult;
import com.coisshi.base.common.annotation.PreventDuplicateSubmit;
import com.coisshi.base.common.exception.BizException;
import com.coisshi.base.module.oss.service.CloudStorageFactory;
import com.coisshi.base.module.oss.vo.OssPolicyResultVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 阿里云OSS操作接口
 *
 * @author coisshi
 * @date 2025/04/28
 */
@Slf4j
@RestController
@RequestMapping("/api/oss")
@RequiredArgsConstructor
public class OssController {

    private final CloudStorageFactory cloudStorageFactory;

    /**
     * 获取OSS上传策略
     *
     * @return 包含上传策略的签名信息
     */
    @GetMapping("/policy")
    public SaResult getPolicy(@RequestParam(value = "dirPrefix", required = false) String dirPrefix) {
        OssPolicyResultVo policy = cloudStorageFactory.getService().getPolicy(dirPrefix);
        return SaResult.ok().setData(policy);
    }
    
    /**
     * 上传文件到OSS
     *
     * @param file 上传的文件
     * @param objectName 对象名称（可选），不传则自动生成
     * @return 文件的访问URL
     */
    @PreventDuplicateSubmit(intervalTime = 5)
    @PostMapping("/upload")
    public SaResult upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "objectName", required = false) String objectName) throws BizException {
        String fileUrl = cloudStorageFactory.getService().uploadFile(file, objectName);
        return SaResult.ok("上传成功").setData(fileUrl);
    }
    
    /**
     * 删除OSS文件
     *
     * @param objectName 对象名称
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public SaResult delete(@RequestParam("objectName") String objectName) throws BizException {
        cloudStorageFactory.getService().deleteFile(objectName);
        return SaResult.ok("删除成功");
    }
} 